package com.yunshipei.core.common;

import com.yunshipei.core.manager.XCloud2Map;
import com.yunshipei.core.model.DeveloperAppModel;
import com.yunshipei.core.model.XCloudAppModel;
import com.yunshipei.core.net.EnterClient;
import com.yunshipei.core.net.ServiceApi;
import com.yunshipei.core.net.convert.JsonConverterFactory;

import org.json.JSONObject;
import org.reactivestreams.Publisher;

import io.reactivex.Flowable;
import io.reactivex.functions.Function;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

public class DeveloperAppHandler {

    private DeveloperAppModel developerAppModel;

    public DeveloperAppHandler(DeveloperAppModel developerAppModel) {
        this.developerAppModel = developerAppModel;
    }

    public Flowable<XCloudAppModel> start() {
        OkHttpClient client = EnterClient.getInstances().getManagerClient();
        ServiceApi serviceApi = new Retrofit.Builder().baseUrl("http://127.0.0.1:1080").client(client).addCallAdapterFactory(RxJava2CallAdapterFactory.create()).addConverterFactory(JsonConverterFactory.create()).build().create(ServiceApi.class);
        return serviceApi.manifest(developerAppModel.getAppPath() + "manifest.json").flatMap(new Function<JSONObject, Publisher<XCloudAppModel>>() {
            @Override
            public Publisher<XCloudAppModel> apply(JSONObject jsonObject) throws Exception {
                XCloudAppModel xCloudAppModel = XCloud2Map.getInstance().parseAdapterPac(jsonObject);
                return Flowable.just(xCloudAppModel);
            }
        });
    }
}
